<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-pink-700 to-rose-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <Mic class="w-8 h-8 text-white"/>
          </div>
          <CardTitle class="text-2xl text-slate-800">{{ t('verbalFluencyTest.testTitle') }}</CardTitle>
          <p class="text-slate-600 mt-2">{{ t('verbalFluencyTest.testDescription') }}</p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="bg-gradient-to-r from-pink-50 to-rose-50 rounded-xl p-6 border border-pink-100">
            <h3 class="font-semibold text-pink-900 mb-4 flex items-center gap-2">
              <Star class="w-5 h-5"/>
              {{ t('verbalFluencyTest.instructionsTitle') }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3"><span class="step-number">1</span>
                <p>{{ t('verbalFluencyTest.instruction1') }}</p></div>
              <div class="flex gap-3"><span class="step-number">2</span>
                <p><strong>{{ t('verbalFluencyTest.semanticFluency') }}</strong>：{{ t('verbalFluencyTest.instruction2Semantic') }}</p></div>
              <div class="flex gap-3"><span class="step-number">3</span>
                <p><strong>{{ t('verbalFluencyTest.phonemicFluency') }}</strong>：{{ t('verbalFluencyTest.instruction3Phonemic') }}</p></div>
              <div class="flex gap-3"><span class="step-number">4</span>
                <p>{{ t('verbalFluencyTest.instruction4Time') }}</p></div>
              <div class="flex gap-3"><span class="step-number">5</span>
                <p><strong>{{ t('verbalFluencyTest.instruction5Important') }}</strong></p></div>
              <div class="flex gap-3"><span class="step-number">6</span>
                <p>{{ t('verbalFluencyTest.instruction6Quality') }}</p></div>
            </div>
          </div>
          <div class="grid md:grid-cols-2 gap-4">
            <div class="task-preview-box border-blue-200 from-blue-50 to-blue-100">
              <div class="flex items-center gap-2 mb-3">
                <Type class="w-5 h-5 text-blue-600"/>
                <h4 class="font-semibold text-blue-800">{{ t('verbalFluencyTest.semanticFluency') }}</h4></div>
              <div class="space-y-1 text-sm text-blue-700">
                <div>• {{ t('verbalFluencyTest.animalNames') }}</div>
                <div>• {{ t('verbalFluencyTest.fruitNames') }}</div>
                <div>• {{ t('verbalFluencyTest.occupationNames') }}</div>
              </div>
            </div>
            <div class="task-preview-box border-purple-200 from-purple-50 to-purple-100">
              <div class="flex items-center gap-2 mb-3">
                <Hash class="w-5 h-5 text-purple-600"/>
                <h4 class="font-semibold text-purple-800">{{ t('verbalFluencyTest.phonemicFluency') }}</h4></div>
              <div class="space-y-1 text-sm text-purple-700">
                <div>• {{ t('verbalFluencyTest.startsWithS') }}</div>
                <div>• {{ t('verbalFluencyTest.startsWithF') }}</div>
                <div>• {{ t('verbalFluencyTest.startsWithL') }}</div>
              </div>
            </div>
          </div>
          <div class="grid md:grid-cols-3 gap-4">
            <div class="info-box from-pink-50 to-pink-100 border-pink-200">
              <div class="info-box-title text-pink-700">6</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.tasks') }}</div>
            </div>
            <div class="info-box from-rose-50 to-rose-100 border-rose-200">
              <div class="info-box-title text-rose-700">60</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.secondsPerTask') }}</div>
            </div>
            <div class="info-box from-pink-50 to-rose-50 border-pink-200">
              <div class="info-box-title text-slate-600">6</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.totalTime') }}</div>
            </div>
          </div>
          <Button class="w-full bg-gradient-to-r from-pink-700 to-rose-600 hover:from-pink-800 hover:to-rose-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                  size="lg"
                  @click="handleStartTest">
            {{ t('verbalFluencyTest.startButton') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div v-else-if="stage === 'test'" class="max-w-4xl mx-auto space-y-6">
    <transition name="slide-down">
      <div v-if="showFeedback" class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50">
        <Card :class="['text-white border-0 shadow-lg', feedbackClass]">
          <CardContent class="py-2 px-4">
            <div class="flex items-center gap-2">
              <CheckCircle class="w-4 h-4"/>
              <span class="font-semibold">{{ feedbackMessage }}</span></div>
          </CardContent>
        </Card>
      </div>
    </transition>

    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <Badge class="bg-pink-100 text-pink-700 border-pink-300" variant="outline">{{ t('verbalFluencyTest.task') }} {{ currentTask + 1 }} /
          {{ ALL_TASKS.length }}
        </Badge>
        <Badge :class="task.type === 'semantic' ? 'bg-blue-100 text-blue-700 border-blue-300' : 'bg-purple-100 text-purple-700 border-purple-300'"
               variant="outline">
          {{ task.type === 'semantic' ? t('verbalFluencyTest.semantic') : t('verbalFluencyTest.phonemic') }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4"/>
          <span class="font-semibold">{{ taskWords.length }} {{ t('verbalFluencyTest.words') }}</span></div>
      </div>
      <div class="flex items-center gap-4">
        <div class="text-center">
          <div :class="['text-2xl font-bold font-mono', taskTimeLeft <= 10 ? 'text-red-500' : 'text-slate-700']">
            {{ taskTimeLeft }}
          </div>
          <div class="text-xs text-slate-500">{{ t('verbalFluencyTest.timeLeft') }}</div>
        </div>
        <div class="text-center">
          <div class="text-lg font-mono text-slate-600">{{ totalScore }}</div>
          <div class="text-xs text-slate-500">{{ t('verbalFluencyTest.qualityScore') }}</div>
        </div>
      </div>
    </div>

    <Progress :model-value="(currentTask / ALL_TASKS.length) * 100" class="h-2"/>

    <Card
      :class="['bg-gradient-to-r', task.type === 'semantic' ? 'from-blue-50 to-blue-100 border-blue-200' : 'from-purple-50 to-purple-100 border-purple-200']">
      <CardContent class="py-4">
        <div class="text-center">
          <h3 :class="['text-xl font-semibold', task.type === 'semantic' ? 'text-blue-800' : 'text-purple-800']">
            {{ task.category }}</h3>
          <p :class="['text-sm mt-1', task.type === 'semantic' ? 'text-blue-700' : 'text-purple-700']">
            {{ task.description }}</p>
        </div>
      </CardContent>
    </Card>

    <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
      <CardContent class="py-8">
        <div class="max-w-md mx-auto space-y-6">
          <div class="flex gap-3">
            <Input ref="inputRef" :value="currentInput" class="text-lg px-4 py-3 border-pink-300 focus:border-pink-500"
                   :placeholder="t('verbalFluencyTest.inputPlaceholder')" @input="currentInput = $event.target.value"
                   @keydown.enter="handleWordSubmit"/>
            <Button :disabled="!currentInput.trim()" class="bg-gradient-to-r from-pink-700 to-rose-600 hover:from-pink-800 hover:to-rose-700 px-6"
                    @click="handleWordSubmit">{{ t('verbalFluencyTest.confirmButton') }}
            </Button>
          </div>
          <div class="text-center text-sm text-slate-500">{{ t('verbalFluencyTest.inputHint') }}</div>
        </div>
      </CardContent>
    </Card>

    <transition name="fade">
      <Card v-if="taskWords.length > 0" class="bg-white/90 backdrop-blur-sm border-slate-200 shadow-lg">
        <CardHeader>
          <CardTitle class="text-lg">{{ t('verbalFluencyTest.enteredWords') }} ({{ taskWords.length }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="flex flex-wrap gap-2">
            <transition-group name="list">
              <div v-for="(word, index) in taskWords" :key="word" class="word-tag">
                <span class="text-slate-700">{{ word }}</span>
                <span class="text-pink-600 ml-2 font-semibold">#{{ index + 1 }}</span>
              </div>
            </transition-group>
          </div>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-pink-700 to-rose-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <Trophy class="w-10 h-10 text-white"/>
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{ t('verbalFluencyTest.testComplete') }}</CardTitle>
          <div class="text-6xl font-bold bg-gradient-to-r from-pink-700 to-rose-600 bg-clip-text text-transparent">
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">{{ t('verbalFluencyTest.verbalFluencyScore') }}</p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div class="info-box from-pink-50 to-pink-100 border-pink-200">
              <div class="info-box-title text-pink-700">{{ results.totalWords }}</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.totalWords') }}</div>
            </div>
            <div class="info-box from-rose-50 to-rose-100 border-rose-200">
              <div class="info-box-title text-rose-700">{{ totalScore }}</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.qualityScore') }}</div>
            </div>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div class="info-box from-blue-50 to-blue-100 border-blue-200">
              <div class="info-box-title text-blue-700">{{ results.semanticCount }}</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.semanticWords') }}</div>
            </div>
            <div class="info-box from-purple-50 to-purple-100 border-purple-200">
              <div class="info-box-title text-purple-700">{{ results.phonemicCount }}</div>
              <div class="info-box-body">{{ t('verbalFluencyTest.phonemicWords') }}</div>
            </div>
          </div>
          <div class="space-y-3">
            <div v-for="(taskResult, index) in results.taskPerformance" :key="index" class="result-row">
              <span class="text-slate-600">{{ taskResult.task }}</span>
              <span class="font-semibold text-slate-800">{{ taskResult.wordCount }} {{ t('verbalFluencyTest.words') }}</span>
            </div>
          </div>
          <Button class="w-full bg-gradient-to-r from-pink-700 to-rose-600 hover:from-pink-800 hover:to-rose-700 text-white py-3 text-lg font-semibold shadow-lg"
                  size="lg"
                  @click="handleComplete">
            {{ t('verbalFluencyTest.viewDetails') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import {ref, computed, watch, nextTick} from 'vue';
import {useI18n} from "vue-i18n";
import {Mic, Clock, Trophy, Star, Type, Hash, CheckCircle} from 'lucide-vue-next';

const emit = defineEmits(['complete']);

const {t} = useI18n();

// --- Constants ---
const SEMANTIC_TASKS = [{
  id: 1,
  type: 'semantic',
  category: t('verbalFluencyTest.categoryAnimal'),
  description: t('verbalFluencyTest.animalNames'),
  duration: 60
}, {id: 2, type: 'semantic', category: t('verbalFluencyTest.categoryFruit'), description: t('verbalFluencyTest.fruitNames'), duration: 60}, {
  id: 3,
  type: 'semantic',
  category: t('verbalFluencyTest.categoryOccupation'),
  description: t('verbalFluencyTest.occupationNames'),
  duration: 60
}];
const PHONEMIC_TASKS = [{
  id: 4,
  type: 'phonemic',
  category: t('verbalFluencyTest.categoryLetterS'),
  description: t('verbalFluencyTest.startsWithS'),
  duration: 60
}, {id: 5, type: 'phonemic', category: t('verbalFluencyTest.categoryLetterF'), description: t('verbalFluencyTest.startsWithF'), duration: 60}, {
  id: 6,
  type: 'phonemic',
  category: t('verbalFluencyTest.categoryLetterL'),
  description: t('verbalFluencyTest.startsWithL'),
  duration: 60
}];
const ALL_TASKS = [...SEMANTIC_TASKS, ...PHONEMIC_TASKS];

// --- State ---
const stage = ref('instructions'); // 'instructions', 'test', 'results'
const currentTask = ref(0);
const currentInput = ref('');
const wordsEntered = ref([]);
const taskWords = ref([]);
const taskTimeLeft = ref(60);
const startTime = ref(0);
const totalScore = ref(0);
const feedbackMessage = ref('');
const showFeedback = ref(false);
const inputRef = ref(null);

let timer = null;

// --- Computed Properties ---
const task = computed(() => ALL_TASKS[currentTask.value]);
const feedbackClass = computed(() => {
  if (feedbackMessage.value.includes('❌')) return 'bg-red-500';
  if (feedbackMessage.value.includes(t('verbalFluencyTest.feedbackAlreadyEntered', {word: ''}).split(' ')[0])) return 'bg-orange-500'; // Check for the start of the translated string
  return 'bg-green-500';
});
const results = computed(() => {
  if (stage.value !== 'results') return {};
  const semanticWords = wordsEntered.value.slice(0, 3).flat();
  const phonemicWords = wordsEntered.value.slice(3).flat();
  const semanticCount = semanticWords.length;
  const phonemicCount = phonemicWords.length;
  const totalWords = semanticCount + phonemicCount;
  const maxPossibleScore = ALL_TASKS.length * 30; // Assumption
  const finalScore = Math.min(100, Math.round((totalScore.value / maxPossibleScore) * 100));
  const taskPerformance = wordsEntered.value.map((words, index) => ({
    task: ALL_TASKS[index].category,
    wordCount: words.length
  }));
  return {finalScore, totalWords, semanticCount, phonemicCount, taskPerformance};
});

// --- Watchers ---
watch([stage, currentTask], (newValues) => {
  if (timer) clearInterval(timer);
  if (newValues[0] === 'test') {
    taskTimeLeft.value = task.value.duration;
    timer = setInterval(() => {
      taskTimeLeft.value--;
      if (taskTimeLeft.value <= 0) {
        handleTaskComplete();
      }
    }, 1000);
    nextTick(() => {
      inputRef.value?.focus();
    });
  }
});

// --- Methods ---
const handleStartTest = () => {
  stage.value = 'test';
  startTime.value = Date.now();
};

const handleWordSubmit = () => {
  const word = currentInput.value.trim().toLowerCase();
  if (!word) return;

  if (taskWords.value.includes(word)) {
    showFeedbackMessage(t('verbalFluencyTest.feedbackAlreadyEntered', {word: word}));
    currentInput.value = '';
    return;
  }

  const {isValid, score, feedback} = task.value.type === 'semantic'
    ? validateSemanticWord(word, task.value.category)
    : validatePhonemicWord(word, task.value.category);

  if (isValid) {
    taskWords.value.push(word);
    totalScore.value += score;
    showFeedbackMessage(`✅ "${word}" +${score}分`);
  } else {
    showFeedbackMessage(feedback);
  }
  currentInput.value = '';
};

const showFeedbackMessage = (msg) => {
  feedbackMessage.value = msg;
  showFeedback.value = true;
  setTimeout(() => showFeedback.value = false, 2000);
};

const validateSemanticWord = (word, category) => {
  const categoryWords = {
    '动物': {
      common: ['猫', '狗', '鸟', '鱼', '马', '牛', '羊', '猪', '鸡', '鸭', '兔子', '老鼠', '青蛙', '蝴蝶', '蜜蜂', '蚂蚁', '虫子', '蛇', '龟', '鹤'],
      uncommon: ['老虎', '狮子', '大象', '熊', '狼', '鹿', '松鼠', '猴子', '熊猫', '企鹅', '海豚', '鲸鱼', '章鱼', '鲨鱼', '螃蟹', '海星', '水母', '孔雀', '鸵鸟', '袋鼠']
    },
    '水果': {
      common: ['苹果', '香蕉', '橙子', '葡萄', '梨', '桃子', '樱桃', '草莓', '西瓜', '芒果', '柠檬', '橘子', '桔子', '李子', '杏子', '椰子', '柚子'],
      uncommon: ['菠萝', '猕猴桃', '火龙果', '榴莲', '荔枝', '龙眼', '山竹', '红毛丹', '莲雾', '释迦', '番石榴', '百香果', '蓝莓', '黑莓', '覆盆子', '石榴', '无花果']
    },
    '职业': {
      common: ['医生', '教师', '护士', '司机', '厨师', '警察', '工人', '农民', '学生', '军人', '老师', '保安', '清洁工', '销售员', '会计', '银行员'],
      uncommon: ['工程师', '律师', '建筑师', '设计师', '程序员', '记者', '演员', '歌手', '画家', '作家', '科学家', '研究员', '翻译', '导演', '摄影师', '心理医生']
    }
  };
  const words = categoryWords[category];
  if (!words) return {isValid: false, score: 0, feedback: t('verbalFluencyTest.feedbackUnknownCategory', {category: category})};
  if (word.length < 2) return {isValid: false, score: 0, feedback: t('verbalFluencyTest.feedbackWordTooShort', {word: word})};
  if (words.common.includes(word)) return {isValid: true, score: 1, feedback: ''};
  if (words.uncommon.includes(word)) return {isValid: true, score: 2, feedback: ''};
  const semanticKeywords = {
    '动物': ['物', '兽', '鸟', '鱼', '虫', '蛇', '龟', '鹤', '鸡', '鸭', '猪', '牛', '羊', '马'],
    '水果': ['果', '子', '梅', '桃', '李', '杏', '柿', '瓜', '莓', '椰', '橙', '柠', '橘'],
    '职业': ['师', '员', '工', '家', '手', '人', '者', '长', '官', '士']
  };
  if ((semanticKeywords[category] || []).some(k => word.includes(k))) return {isValid: true, score: 1, feedback: ''};
  return {isValid: false, score: 0, feedback: t('verbalFluencyTest.feedbackNotBelongToCategory', {word: word, category: category})};
};

const validatePhonemicWord = (word, category) => {
  const letter = category.match(/"([A-Z])"/)?.[1]?.toLowerCase();
  if (!letter) return {isValid: false, score: 0, feedback: t('verbalFluencyTest.feedbackCannotRecognizeLetter')};
  if (word.length < 2) return {isValid: false, score: 0, feedback: t('verbalFluencyTest.feedbackWordTooShort', {word: word})};
    if (!word.startsWith(letter)) return {
    isValid: false,
    score: 0,
    feedback: t('verbalFluencyTest.feedbackNotStartWith', {word: word, letter: letter.toUpperCase()})
  };
  let score = 1;
  if (word.length >= 4) score = 2;
  if (word.length >= 6) score = 3;
  if (['的', '化', '性', '者', '员'].some(c => word.includes(c))) score += 1;
  return {isValid: true, score, feedback: ''};
};

const handleTaskComplete = () => {
  wordsEntered.value.push(taskWords.value);
  if (currentTask.value < ALL_TASKS.length - 1) {
    currentTask.value++;
    taskWords.value = [];
  } else {
    stage.value = 'results';
  }
};

const handleComplete = () => {
  const res = results.value;
  emit('complete', {
    id: Date.now().toString(),
    testType: 'verbal-fluency',
    score: res.finalScore,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: {
      totalWords: res.totalWords,
      totalQualityScore: totalScore.value,
      semanticWords: res.semanticCount,
      phonemicWords: res.phonemicCount,
      averageWordsPerTask: Math.round(res.totalWords / ALL_TASKS.length * 10) / 10,
      taskPerformance: res.taskPerformance,
      fluencyIndex: Math.round((totalScore.value / ALL_TASKS.length) * 10) / 10
    }
  });
};

</script>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.slide-down-enter-active, .slide-down-leave-active {
  transition: all 0.3s ease-out;
}

.slide-down-enter-from, .slide-down-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.list-enter-active, .list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: scale(0.8);
}

.step-number {
  @apply w-6 h-6 bg-pink-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5;
}

.task-preview-box {
  @apply bg-gradient-to-br rounded-xl p-4 border;
}

.info-box {
  @apply text-center p-4 bg-gradient-to-br rounded-xl border;
}

.info-box-title {
  @apply text-2xl font-bold mb-1;
}

.info-box-body {
  @apply text-sm;
}

.result-row {
  @apply flex justify-between items-center p-3 bg-slate-50 rounded-lg;
}

.word-tag {
  @apply bg-gradient-to-r from-pink-100 to-rose-100 border border-pink-200 rounded-lg px-3 py-1 text-sm;
}
</style>
